<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入合同名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="合同编码" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="审核状态" prop="auditState">
        <el-select v-model="queryParams.auditState" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.contract_audit_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="录入时间" prop="inputTime">
        <el-date-picker clearable v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" placeholder="请选择录入时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['businessManagement:contract:add']">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange" :border="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="60" />
      <el-table-column label="客户" :formatter="sfktCustomer" align="center" prop="customerId" width="120" />
      <el-table-column label="合同名称" align="center" prop="contractName" width="120" />
      <el-table-column label="合同编码" align="center" prop="contractCode" width="100" />
      <el-table-column label="合同金额(单位:万元)" align="center" prop="amounts" width="90" />
      <el-table-column label="合同开始日期" align="center" prop="startDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同结束日期" align="center" prop="endDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="电子附件" align="center" prop="appendix" width="100">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-place" type="primary" @click="downLoadFile(scope.row.appendix)">下载</el-button>
          <!-- <el-button align="center" size="medium" @click="downLoadFile(scope.row.appendix)" icon="el-icon-caret-right">下载</el-button> -->
          <!-- <el-button type="warning" round @click="downLoadFile(scope.row.appendix)">下载</el-button> -->
        </template>
      </el-table-column>

      <el-table-column label="录入人" :formatter="sfktUser" align="center" prop="inputUser" />
      <el-table-column label="录入时间" align="center" prop="inputTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inputTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="审核状态" align="center" prop="auditState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_audit_status" :value="scope.row.auditState" />
        </template>
      </el-table-column>

      <el-table-column label="是否盖章确认" :formatter="sfktAffixSeal" align="center" prop="affixSealState">
        <template slot-scope="scope">
          <el-tag :type="scope.row.affixSealState == 0 ? 'danger'
              : scope.row.affixSealState == 1
                ? 'success'
                : 'danger'" disable-transitions>{{ scope.row.affixSealState == 0 ? '否'
        : scope.row.affixSealState == 1
          ? '是'
          : '拒绝' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="sfktnullify" label="是否作废" :formatter="sfktnullify" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.nullifyState == -1 ? 'danger'
              : scope.row.nullifyState == 0
                ? 'success'
                : 'danger'" disable-transitions>{{ scope.row.nullifyState == -1 ? '作废'
        : scope.row.nullifyState == 0
          ? '在用'
          : '拒绝' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350px">
        <template slot-scope="scope">
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            :disabled="isEdit(scope.row)" v-hasPermi="['businessManagement:contract:edit']">修改</el-button>
          <!-- <el-button type="warning" icon="el-icon-star-off" circle></el-button> -->
          <!-- <el-button circle icon="el-icon-place" type="primary" @click="downLoadFile(scope.row.appendix)">下载</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-success" :disabled="isAuditYes(scope.row)"
            @click="handleAuditYes(scope.row)">审核通过</el-button>

          <el-button size="mini" type="text" icon="el-icon-error" :disabled="isAuditNo(scope.row)"
            @click="handleAuditNo(scope.row)">审核不通过</el-button>

          <el-button size="mini" type="text" icon="el-icon-s-goods" :disabled="isSeal(scope.row)"
            @click="handleSeal(scope.row)">确认盖章</el-button>

          <el-button size="mini" type="text" icon="el-icon-platform-eleme" :disabled="isInvalid(scope.row)"
            @click="handleInvalid(scope.row)">作废</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col span="12">
            <div>
              <el-form-item label="客户" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择">
                  <el-option v-for="custom in customers" :key="custom.id" :label="custom.customerName"
                    :value="custom.id"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col span="12">
            <div>
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="form.contractName" placeholder="请输入合同名称" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col span="12">
            <div>
              <el-form-item label="合同编码" prop="contractCode">
                <el-input v-model="form.contractCode" placeholder="请输入合同编码" />
              </el-form-item>
            </div>
          </el-col>
          <el-col span="12">
            <div>
              <el-form-item label="合同金额" prop="amounts">
                <el-input v-model="form.amounts" placeholder="请输入合同金额" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col span="12">
            <div>
              <el-form-item label="合同开始时间" prop="startDate">
                <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择合同开始时间">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          <el-col span="12">
            <div>
              <el-form-item label="合同结束时间" prop="endDate">
                <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择合同结束时间">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-form-item label="附件">
          <file-upload v-model="form.appendix" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadAnnex, InvalidYes, sealYes, auditNo, auditYes, listContract, getContract, delContract, addContract, updateContract } from "@/api/businessManagement/contract";
import { listUsers } from "@/api/system/user";
import { listCustoms } from "@/api/custom/cusInfo";
import { customerName } from "@/api/customer/linkman";

import { CONTRACT_SEAL_NO, CONTRACT_SEAL_YES, CONTRACT_EFFECTIVE, CONTRACT_INVALID, CONTRACT_AUDIT_INIT, CONTRACT_AUDIT_YES, CONTRACT_AUDIT_NO } from "@/store/modules/bus-contract-constant";
//引入download，这是若依框架自带的，在utils/request里面封装好的方法
import { download } from "@/utils/request";
export default {
  name: "Contract",
  dicts: ['contract_audit_status'],
  data() {
    return {
      // 隐藏或显示审核通过
      flag1: true,
      flag2: true,
      flag3: true,
      // 所有的客户
      customers: [],
      // 所有用户
      users: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 录入时间时间范围
      daterangeStartDate: [],
      // 录入时间时间范围
      daterangeEndDate: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        contractName: null,
        contractCode: null,
        startDate: null,
        endDate: null,
        auditState: null,
        inputTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "客户id不能为空", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        contractCode: [
          { required: true, message: "合同编码不能为空", trigger: "blur" }
        ],
        amounts: [
          { required: true, message: "合同金额不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "合同生效开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "合同生效结束时间不能为空", trigger: "blur" }
        ],
        appendix: [
          { required: true, message: "附件不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 根据用户id获取名字
    getuser(row) {
      let userName = '';
      for (let user of this.users) {
        if (user.userId == row.cusEnterPeopleId) {
          userName = user.userName;
        }
      }
      return userName;
    },

    // 是否盖章
    // (0:否 1:是)
    sfktAffixSeal(row, index) {
      if (row.affixSealState == 0) {
        return "否";
      } else if (row.affixSealState == 1) {
        return "是";
      }
    },
    sfktnullify(row, index) {
      if (row.nullifyState == 0) {
        return "在用";
      } else if (row.nullifyState == -1) {
        return "作废";
      }
    },
    sfktUser(row, index) {
      let inputName = "";
      for (let user of this.users) {
        if (user.userId == row.inputUser) {
          inputName = user.userName;
          return inputName;
        }
      }
    },
    sfktCustomer(row, index) {
      let cusName = "";
      for (let customer of this.customers) {
        if (customer.id == row.customerId) {
          cusName = customer.customerName;
          return cusName;
        }
      }
    },

    /** 查询合同信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeStartDate && '' != this.daterangeStartDate) {
        this.queryParams.params["beginStartDate"] = this.daterangeStartDate[0];
        this.queryParams.params["endStartDate"] = this.daterangeStartDate[1];
      }
      if (null != this.daterangeEndDate && '' != this.daterangeEndDate) {
        this.queryParams.params["beginEndDate"] = this.daterangeEndDate[0];
        this.queryParams.params["endEndDate"] = this.daterangeEndDate[1];
      }
      listContract(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listUsers().then(res => {
        this.users = res.data;
      });
      customerName().then(res => {
        this.customers = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerId: null,
        contractName: null,
        contractCode: null,
        amounts: null,
        startDate: null,
        endDate: null,
        appendix: null,
        affixSealState: null,
        auditState: null,
        nullifyState: null,
        inputUser: null,
        inputTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        contractName: null,
        contractCode: null,
        startDate: null,
        endDate: null,
        auditState: null,
        inputTime: null
      };
      this.daterangeStartDate = [];
      this.daterangeEndDate = [];
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同信息编号为"' + ids + '"的数据项？').then(function () {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 审核通过按钮操作 */
    handleAuditYes(row) {
      const id = row.id;
      const auditState = row.auditState;
      this.$modal.confirm('是否要审核通过').then(function () {
        return auditYes(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => { });
    },

    /** 审核通过按钮操作 */
    handleAuditNo(row) {
      const id = row.id;
      const auditState = row.auditState;
      this.$modal.confirm('是否审核不通过').then(function () {
        return auditNo(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },

    /** 确认盖章按钮操作 */
    handleSeal(row) {
      const id = row.id;
      const affixSealState = row.affixSealState;
      this.$modal.confirm('是否要盖章').then(function () {
        return sealYes(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },

    /** 作废按钮操作 */
    handleInvalid(row) {
      const id = row.id;
      const nullifyState = row.nullifyState;
      this.$modal.confirm('是否要作废该合同').then(function () {
        return InvalidYes(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },




    /**
     * 下载文件
     * @param value value是文件的路径，就是你正常存到数据里的那个参数/profile/upload什么的
     * 整体代码都不需要变，你只需要调用这个我写的downLoadFile(value)函数，在点击下载按钮的时候，通过@click方法调用这个函数，传入那个文件路径就行，文件路径就是若依框架的/profile/upload/日期/文件名那个路径，这个路径看不懂就不要用了！
     */
    downLoadFile(value) {
      //根据文件路径参数，按斜杠进行分割，取得文件名，这是download函数需要的第三个参数
      let list = value.split("/");
      let fileName = list[list.length - 1];
      //这是文件路径参数，因为download函数需要传三个参数，这是第二个参数
      let params = {
        resource: value
      }
      /** request里面的download下载函数 */
      //download函数是若依自带的，第一个参数是请求的url路径，不需要变，这个路径下的controller后台方法也是若依写好封装好了的。
      download("/common/download/resource", params, fileName);
      console.log("文件名");
      console.log("value");
    },

    //  /** 下载附件按钮操作 */
    //  handleDownload(row) {
    //   const appendix = row.appendix;
    //   const id = row.id;
    //   this.$modal.confirm('是否要下载该附件').then(function() {
    //     return downloadAnnex(appendix);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("下载成功");
    //   }).catch(() => {});
    // },


    // /** 下载附件按钮操作 */
    // handleDownload(row) {
    //   var filename = row.appendix;
    //   function download(appendix) {
    //         $.modal.confirm("确定要文件下载吗？", function() {
    //         //将路径名一部分/upload/2021/05/10/xxx.jpg传给controller
    //             location.href = ctx+'common/download/resource'+filename.substring(filename.lastIndexOf("/upload"));
    //         });
    //     }

    // },



    /** 导出按钮操作 */
    handleExport() {
      this.download('businessManagement/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    },
    // 是否审核通过
    isAuditYes(row) {
      let auditState = row.auditState;
      let nullifyState = row.nullifyState;
      return !(auditState == CONTRACT_AUDIT_INIT && nullifyState == CONTRACT_EFFECTIVE);
    },
    // 是否审核不予通过
    isAuditNo(row) {
      let auditState = row.auditState;
      let nullifyState = row.nullifyState;
      return !(auditState == CONTRACT_AUDIT_INIT && nullifyState == CONTRACT_EFFECTIVE);
    },

    // 是否修改
    isEdit(row) {
      let auditState = row.auditState;
      let nullifyState = row.nullifyState;
      return !(auditState == CONTRACT_AUDIT_INIT && nullifyState == CONTRACT_EFFECTIVE);
    },
    // 是否盖章
    isSeal(row) {
      let auditState = row.auditState;
      let nullifyState = row.nullifyState;
      let affixSealState = row.affixSealState;
      return !(auditState == CONTRACT_AUDIT_YES && nullifyState == CONTRACT_EFFECTIVE && affixSealState == CONTRACT_SEAL_NO);
    },
    // 是否作废
    isInvalid(row) {
      let auditState = row.auditState;
      let affixSealState = row.affixSealState;
      let nullifyState = row.nullifyState;
      return (nullifyState == CONTRACT_INVALID);
      // || affixSealState == CONTRACT_SEAL_YES
    },
  }
};
</script>
